package hqb.dev.webdeploy.logic;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import hqb.dev.webdeploy.api.DeployPrm;
import hqb.dev.webdeploy.flow.FlowStep;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 更新配置对象
 *
 * @author HQB--2024-04-22
 **/
@Data
@Slf4j
public class UpdateFlow {
    /**
     * 流程解析状态,默认false,表示解析失败,不更新
     */
    private boolean state = false;

    private List<FlowStep> steps;

    public UpdateFlow(DeployPrm prm, File unzipDir) {
        String path = prm.getPath();
        if (unzipDir.exists()) FileUtil.del(unzipDir);
        FileUtil.mkdir(unzipDir);
        File file = new File(path);
        if (!file.exists()) {
            log.info("更新包不存在: " + path);
            return;
        }
        if (!file.isFile()) {
            log.info("更新包不是文件: " + path);
            return;
        }
        log.info("开始解压文件: " + path);
        File unzip = ZipUtil.unzip(file, unzipDir);
        log.info("解压完成,解压目录: " + unzip.getAbsolutePath());
        File update = new File(unzip, "update.json");
        if (!update.exists()) log.info("更新包中没有[update.json]文件.");
        JSONObject entries = file2Json(update);
        this.steps = FlowStep.parse(entries, prm, unzipDir);
        this.state = true;
    }

    private JSONObject file2Json(File update) {
        List<String> strings = FileUtil.readLines(update, StandardCharsets.UTF_8);
        String jsonstr = strings.stream().map(x -> x.replaceAll("//.+", "")).filter(x -> StrUtil.isNotEmpty(x.trim())).collect(Collectors.joining());
        return JSONUtil.parseObj(jsonstr);
    }

}
